package kr.hkit.powerjava.chapter24.work;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class StudentDao implements InterfaceStudent<Student>{
	private static final String FILE="stdlist.data";
	private ArrayList<Student> arList=new ArrayList<>();
	//생성자
	public StudentDao(){
		loadList();
	}
	@Override
	public void insertItem(Student item) {
		arList.add(item);
		
	}

	@Override
	public void deleteItem(Student item) {
		arList.remove(item);
		
	}

	@Override
	public void updateItem(Student item) {
		arList.set(arList.indexOf(item), item);
		
	}

	@Override
	public void prnItem() {
		for(Student std:arList){
			System.out.println(std);
		}
		
	}
	/*public void prnItem(ArrayList<Student> list){
		for(Student std:arList){
			System.out.println(std);
		}
	}*/
	@Override
	public Student searchItem(Student item) {
		if(arList.contains(item)){
			return arList.get(arList.indexOf(item));
		}else{
		return null;
	}
	}
	@Override
	public void loadList() {
		ObjectInputStream ois=null;
		//ArrayList<Student> list= null;
		try {
			ois= new ObjectInputStream(new BufferedInputStream(new FileInputStream(StudentDao.FILE)));
			arList=(ArrayList<Student>)ois.readObject();
		} catch (Exception e) {
			File file= new File(StudentDao.FILE);
			try {
				file.createNewFile();
				arList= new ArrayList<>();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			//System.err.println(e);
		}finally{
			if(ois!=null)try{ois.close();}catch (Exception e) {
			}
		}
		
	}

	@Override
	public void saveList() {
		ObjectOutputStream oos=null;
		try {
			oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(StudentDao.FILE)));
			oos.writeObject(arList);
			oos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(oos!=null)try{oos.close();}catch (Exception e) {
				// TODO: handle exception
			}
		}
		
	}
	
}
